package com.library.service;

import com.library.dao.BookInfoDao;
import com.library.dao.LendListDao;
import com.library.dao.ReaderInfoDao;
import com.library.domain.BookInfo;
import com.library.domain.LendList;
import com.library.domain.ReaderInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Service
public class BookLendServiceImpl implements BookLendService{
    @Resource
    private BookInfoDao bookInfoDao;
    @Resource
    private LendListDao lendListDao;
    @Resource
    private ReaderInfoDao readerInfoDao;
     @Override
    public List<BookInfo> queryBookInfo() {
        return bookInfoDao.selectBookInfo();
    }

    @Override

    /*
    * 借阅服务：
    *
    *
    *
    * */
    @Transactional
    public int bookLend(Integer id,String username) {
        /*
        * 1、改变图书信息status
        * 2、更新图书借阅信息历史记录
        * */
       int count= bookInfoDao.updateBookLendStatus(id);
        if(count==1){
            /*

            * 更新书库成功，开始更新借阅历史

            * */
            BookInfo bookInfo=bookInfoDao.selectBookById(id);

            LendList lendList=new LendList();
            lendList.setBookId(id);
            /*
            * 获取当前用户名
            * 1、根据用户名查询id
            * */
           ReaderInfo readerInfo= readerInfoDao.selectForLogIn(username).get(0);
            lendList.setReaderId(readerInfo.getId());
            SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           String lendDate= sd.format(new Date());
            String backDate= sd.format(new Date());
            lendList.setLendDate(lendDate);
            lendList.setBackDate(backDate);
            lendList.setBackType(0);

            lendList.setExceptRemarks("图书信息："+bookInfo.toString());
            int lendResult=lendListDao.insertLendList(lendList);
            if(lendResult==1){
                /*
                * 更新历史记录成功
                * */
                return 1;
            }else{
                return 0;
            }


        }else{
            /*
            * 抛出异常，或者返回失败页面
            * */
            return 0;
        }

    }
}
